package com.baibei.pay.withdraw;

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.InputFilter;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baibei.basic.IPresenter;
import com.baibei.basic.module.utils.SMSCountDownTimer;
import com.baibei.ebec.sdk.IPushApi;
import com.baibei.model.BalanceInfo;
import com.baibei.model.BankInfo;
import com.baibei.model.CityInfo;
import com.baibei.model.UserInfo;
import com.baibei.module.AppRouter;
import com.baibei.module.BasicActivity;
import com.baibei.pay.R;
import com.baibei.pay.R2;
import com.baibei.pay.recharge.SimpleTextWatcher;
import com.baibei.pay.selector.InfoSelecterFragment;
import com.baibei.pay.selector.OnSelectListener;
import com.baibei.pay.selector.ProvinceCityFragment;
import com.baibei.ui.AppUI;
import com.baibei.widget.CashierInputFilter;
import com.blankj.utilcode.utils.LogUtils;
import com.rae.swift.Rx;
import com.rae.swift.session.SessionManager;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 提现界面操作
 * shenminjie 2017-08-16
 */
@Route(path = AppRouter.ROUTER_USER_WITHDRAW)
public class WithdrawActivity extends BasicActivity implements WithdrawContract.WithdrawView {

    @BindView(R2.id.et_recharge_count)
    EditText mEtWithdrawAmout;
    @BindView(R2.id.tv_service_fee)
    TextView mTvServiceFee;
    @BindView(R2.id.tv_choose_bank)
    TextView mTvChooseBank;
    @BindView(R2.id.et_bank_card_num)
    EditText mEtBankCardNum;
    @BindView(R2.id.tv_choose_province_city)
    TextView mTvChooseProvinceCity;
    @BindView(R2.id.et_bank_name)
    EditText mEtBankName;
    @BindView(R2.id.et_bankcard_username)
    EditText mEtBankcardUsername;
    @BindView(R2.id.et_checkcode)
    EditText mEtCheckcode;
    @BindView(R2.id.tv_get_checkcode)
    TextView mTvGetCheckcode;
    @BindView(R2.id.tv_commit)
    TextView mTvCommit;
    @BindView(R2.id.tv_fund_time)
    TextView mTvFundTime;

    /**
     * 倒计时
     */
    private SMSCountDownTimer mSMSCountDownTimer = new SMSCountDownTimer();

    /**
     * 展示层
     */
    private WithdrawContract.Presenter mPresenter;

    /**
     * 输入密码
     */
    private String mPassword;

    /**
     * 选择银行
     */
    private BankInfo mSelectBankInfo;

    /**
     * 选中的开户省市
     */
    private CityInfo mCityInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_withdrawal_amount);
        ButterKnife.bind(this);

        mPassword = getIntent().getStringExtra("password");
        initView();
        mPresenter = inject(WithdrawContract.Presenter.class);
        mPresenter.getBalanceAndBankList();
    }

    /**
     * 初始化
     */
    private void initView() {
        //添加监听操作- - -银行列表更省市的也要更新
        mEtWithdrawAmout.addTextChangedListener(mTextWatcher);
        mEtBankCardNum.addTextChangedListener(mTextWatcher);
        mEtBankName.addTextChangedListener(mTextWatcher);
        mEtBankcardUsername.addTextChangedListener(mTextWatcher);
        mEtCheckcode.addTextChangedListener(mTextWatcher);

        //订货服务费监听
        mEtWithdrawAmout.addTextChangedListener(mServiceFeeWatcher);
    }

    @Override
    public IPresenter getBasicPresenter() {
        return mPresenter;
    }

    @OnClick(R2.id.tv_get_checkcode)
    public void onCheckcodeClickListener() {
        if (mSMSCountDownTimer.isFinish()) {
            mPresenter.getCheckCode();
            mSMSCountDownTimer.start(this);
        }
    }

    @OnClick(R2.id.tv_choose_bank)
    public void onBankSelectListener() {
        //选择银行
        if (mPresenter.getBankInfos() != null && mPresenter.getBankInfos().size() != 0) {
            //显示bank选择器
            new InfoSelecterFragment<BankInfo>().setInfos(mPresenter.getBankInfos()).setListener(new OnSelectListener<BankInfo>() {
                @Override
                public void onDefineListener(BankInfo bankInfo, DialogFragment fragment) {
                    mSelectBankInfo = bankInfo;
                    //刷新视图
                    mTvChooseBank.setText(mSelectBankInfo.getBankName());
                    updateBtnEnable();
                    fragment.dismiss();
                }

                @Override
                public void onCancle(DialogFragment fragment) {
                    fragment.dismiss();
                }
            }).show(getSupportFragmentManager(), "tag");
        }
    }

    @OnClick(R2.id.tv_choose_province_city)
    public void onProvinceCitySelectListener() {
        //选择省市
        new ProvinceCityFragment().setInfos(mPresenter.getProvinceInfos()).setListener(new OnSelectListener<CityInfo>() {
            @Override
            public void onDefineListener(CityInfo cityInfo, DialogFragment fragment) {
                mCityInfo = cityInfo;
                mTvChooseProvinceCity.setText(cityInfo.getProvince() + " " + cityInfo.getName());
                updateBtnEnable();
                fragment.dismiss();
            }

            @Override
            public void onCancle(DialogFragment fragment) {
                fragment.dismiss();
            }
        }).show(getSupportFragmentManager(), ProvinceCityFragment.class.getName());
    }


    @OnClick(R2.id.tv_commit)
    public void commit() {
        //提现
        mPresenter.withdrawAmount();
    }

    @Override
    protected void onDestroy() {
        if (mSMSCountDownTimer != null) {
            mSMSCountDownTimer.cancel();
        }
        super.onDestroy();
    }

    @Override
    public void onSmsSuccess() {
        AppUI.success(getContext(), "短信验证码发送成功");
    }

    @Override
    public void onSmsFailed(String s) {
        AppUI.failed(getContext(), s);
    }

    @Override
    public void onSmsCountDown(int i, String s) {
        mTvGetCheckcode.setText(s);
    }

    @Override
    public void onSmsCountDownFinish() {
        mSMSCountDownTimer.cancel();
        mTvGetCheckcode.setText(R.string.reload_checkcode);
    }

    @Override
    public void onLoadBasicDataFailed(String msg) {
        AppUI.failed(this, msg);
    }

    @Override
    public void onLoadBalanceInfo(BalanceInfo info) {
        LogUtils.e("余额:" + info + "");
        CashierInputFilter inputFilter = new CashierInputFilter();
        inputFilter.setMaxValue(info.getBalance());
        //等获取余额后进行最大值的操作
        mEtWithdrawAmout.setFilters(new InputFilter[]{inputFilter});
        mEtWithdrawAmout.setHint(String.format(getString(R.string.available_amount), Rx.formatPrice(info.getBalance())));
    }

    @Override
    public void onLoadBankList(List<BankInfo> infos) {
        LogUtils.e("银行列表:" + infos + "");
    }

    @Override
    public String getPhone() {
        UserInfo userInfo = SessionManager.getDefault().getUser();
        return userInfo == null ? "" : userInfo.getMobile();
    }

    @Override
    public String getCheckCodeType() {
        return IPushApi.SMS_TYPE_WITHDRAW;
    }

    @Override
    public String getWithdrawAmount() {
        double amount = Rx.parseDouble(mEtWithdrawAmout.getEditableText().toString(), 0.0f);
        return amount == 0 ? "" : amount + "";
    }

    @Override
    public String getCity() {
        return mCityInfo == null ? "" : mCityInfo.getName();
    }

    @Override
    public String getProvince() {
        return mCityInfo == null ? "" : mCityInfo.getProvince();
    }

    @Override
    public String getBankCode() {
        return mSelectBankInfo == null ? "" : mSelectBankInfo.getBankCode();
    }

    @Override
    public String getSubBank() {
        return mEtBankName.getEditableText().toString();
    }

    @Override
    public String getBankAccount() {
        return mEtBankCardNum.getEditableText().toString();
    }

    @Override
    public String getRealName() {
        return mEtBankcardUsername.getEditableText().toString();
    }

    @Override
    public String getFundPassword() {
        return mPassword;
    }

    @Override
    public String getCheckCode() {
        return mEtCheckcode.getEditableText().toString();
    }

    @Override
    public void showLoading() {
        AppUI.loading(this);
    }

    @Override
    public void hideLoading() {
        AppUI.dismiss();
    }

    @Override
    public void showWithdrawLoading() {
        AppUI.loading(this, "提现操作中");
    }

    @Override
    public void onWithdrawFailed(String msg) {
        AppUI.failed(this, msg);
    }

    @Override
    public void onWithdrawSuccess() {
        //提现成功，显示成功操作
        WithdrawSuccessFragment fragment = new WithdrawSuccessFragment();
        fragment.setOnListener(new WithdrawSuccessFragment.OnSuccessListener() {
            @Override
            public void onSuccessListener(DialogFragment fragment) {
                //成功返回
                fragment.dismiss();
                finish();
            }
        });
        fragment.show(getSupportFragmentManager(), "success");
    }

    @Override
    public void onLoadFundTimeInfo(String msg) {
        mTvFundTime.setText(msg);
    }

    /**
     * 更新提交按钮是否可用
     */
    private boolean getBtnEnable() {
        //金额的输入
        if (TextUtils.isEmpty(getWithdrawAmount())) {
            return false;
        }
        //选择银行
        if (mSelectBankInfo == null) {
            return false;
        }
        //银行卡号
        if (TextUtils.isEmpty(getBankAccount())) {
            return false;
        }
        //开户省市
        if (TextUtils.isEmpty(getProvince()) || TextUtils.isEmpty(getCity())) {
            return false;
        }
        //开户支行
        if (TextUtils.isEmpty(getSubBank())) {
            return false;
        }
        //账户姓名
        if (TextUtils.isEmpty(getRealName())) {
            return false;
        }
        //最后检验验证码
        return !TextUtils.isEmpty(getCheckCode());
    }

    /**
     * 监听输入操作
     */
    SimpleTextWatcher mTextWatcher = new SimpleTextWatcher() {
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            //监听是否可以调用
            updateBtnEnable();
        }
    };

    /**
     * 订货服务费监听事件
     */
    SimpleTextWatcher mServiceFeeWatcher = new SimpleTextWatcher() {
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            double price = Rx.parseDouble(charSequence);
            //100以内收取2元，以外的不收
            if (price > 0 && price < 101) {
                mTvServiceFee.setText(String.format(getString(R.string.withdraw_service_fee), Rx.formatPrice(2)));
            } else {
                mTvServiceFee.setText(String.format(getString(R.string.withdraw_service_fee), Rx.formatPrice(0)));
            }
        }
    };

    /**
     * 更新按钮状态
     */
    private void updateBtnEnable() {
        mTvCommit.setEnabled(getBtnEnable());
    }
}
